package com.strongbj;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.ServiceManager;
import com.strongbj.core.server.CollectionServer;
import com.strongbj.iot.devices.newlight.message.NewLightReaderMessageHandleFactory;

@Service
public class ServerManager {
	private final static Logger logger = LogManager.getLogger(ServerManager.class);

	private ServiceManager serviceManager;
	
	@Value("${rs.server.name}")
	private String rsServerName;
	@Value("${rs.server.port}")
	private int rsServerPort;
	@Value("${rs.server.readTimeout}")
	private int rsServerReadTimeout;
	
	@PostConstruct
	public void init() {
		List<com.google.common.util.concurrent.Service> services = Lists.newArrayList();
		CollectionServer rsServer = new CollectionServer();
		rsServer.setServerName(this.rsServerName);
		rsServer.setServerPort(this.rsServerPort);
		rsServer.setReadTimeout(this.rsServerReadTimeout);
		rsServer.setMessageHandleFactory(new NewLightReaderMessageHandleFactory());
		services.add(rsServer);

		this.serviceManager = new ServiceManager(services);
		serviceManager.addListener(new ServiceManager.Listener() {

			@Override
			public void healthy() {
				logger.info("服务运行健康！");
			}

			@Override
			public void stopped() {
				logger.info("服务运行结束！");
			}

			@Override
			public void failure(com.google.common.util.concurrent.Service service) {
				logger.info("服务运行失败！");
			}

		}, MoreExecutors.directExecutor());
		serviceManager.startAsync();
	}

	/**
	 * 应用停止前关闭所有服务程序
	 * @throws TimeoutException
	 */
	@PreDestroy
	public void destory() throws TimeoutException {
		serviceManager.stopAsync().awaitStopped(30, TimeUnit.SECONDS);
	}
}
